package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import pojo.Warehouse;
import util.DBUtils;
import dao.WarehouseDao;

public class WarehouseDaoImpl extends BaseDaoImpl<Warehouse> implements WarehouseDao {

	@Override
	public int add(Warehouse warehouse) {
		String sql = "insert into warehouse values(?,?)";
		PreparedStatement pst = null;
		int m = 0;
		Connection conn = DBUtils.createConnection();
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, UUID.randomUUID().toString());
			pst.setString(2, warehouse.getAddr());
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error(e);
		}finally{
			DBUtils.close(conn, pst, null);
		}
		return m;
	}

	@Override
	public int delete(String id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int update(Warehouse t) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Warehouse load(String id) {
		String sql = "select * from warehouse where id=?";
		Connection conn = DBUtils.createConnection();
		PreparedStatement pst = null;
		ResultSet rs = null;
		Warehouse warehouse =null;
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, id);
			rs = pst.executeQuery();
			if (rs.next()) {
				warehouse = new Warehouse();
				warehouse.setId(rs.getString("id"));
				warehouse.setAddr(rs.getString("addr"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}finally{
			DBUtils.close(conn, pst, rs);
		}
		return warehouse;	
	}


	@Override
	public List<Warehouse> findAll() {
		String sql = "select * from warehouse";
		Connection conn = DBUtils.createConnection();
		PreparedStatement pst = null;
		ResultSet rs = null;
		List<Warehouse> warehouses = new ArrayList<>(); 
		try {
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			while(rs.next()) {
				Warehouse warehouse = new Warehouse();
				warehouse.setId(rs.getString("id"));
				warehouse.setAddr(rs.getString("addr"));
				warehouses.add(warehouse);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}finally{
			DBUtils.close(conn, pst, rs);
		}
		return warehouses;	
	}

}
